package com.demo.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.config.AlipayConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.config.MovieFeignClient;
import com.demo.controller.consumerFrom.OrderCreateConsumerFrom;
import com.demo.controller.consumerFrom.OrderLogConsumerFrom;
import com.demo.controller.from.MovieAddMoneyFrom;
import com.demo.controller.from.MovieOrderFrom;
import com.demo.controller.from.MovieScoreFrom;
import com.demo.controller.from.MovieScoreListFrom;
import com.demo.exetion.MainExection;
import com.demo.model.MovieOrder;
import com.demo.dao.MovieOrderDao;
import com.demo.model.MovieTicketing;
import com.demo.service.MovieOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.service.MovieTicketingService;
import com.demo.utils.CommonUtil;
import com.demo.utils.Result;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杨森
 * @since 2022-04-07
 */
@Service
public class MovieOrderServiceImpl extends ServiceImpl<MovieOrderDao, MovieOrder> implements MovieOrderService {
    @Resource
    private MovieTicketingService movieTicketingService;

    @Resource
    private MovieFeignClient movieFeignClient;

    @Autowired
    private RedisTemplate<String, Object> ort;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addMovieOrder(MovieOrderFrom movieOrderFrom) throws MainExection {
        //判断验证码
        String code = movieOrderFrom.getCode();
        Object o1 = ort.opsForValue().get("iphone:" + movieOrderFrom.getUserPhone());
        if (o1!=null){
            if (!o1.toString().equals(code)){
                throw new MainExection(500,"验证码不正确");
            }
        }else{
            throw new MainExection(500,"请先获取验证码");
        }
        //获取票务id集合
        List<Integer> ticketingIds = movieOrderFrom.getTicketingIds();
        //循环判断票务的状态
        Double money=0.0;
        Integer numberOfSessionsId=0;
        for (Integer ticketingId : ticketingIds) {
            MovieTicketing movieTicketing = movieTicketingService.getById(ticketingId);
            if (numberOfSessionsId==0){
                numberOfSessionsId=movieTicketing.getNumberOfSessionsId();
            }else if (numberOfSessionsId !=movieTicketing.getNumberOfSessionsId()) throw new MainExection(500,"不能同时购买两个场次的票");
            String price = movieTicketing.getPrice();
            double v = Double.parseDouble(price);
            money+=v;
            if (movieTicketing.getOrderId() !=null) throw new MainExection(500,"id为"+ticketingId+"的票务已被购买");

        }
        //发送手机验证码到手机验证身份
        //将票务id 记录订单
        String s = money.toString();
        MovieOrder build = MovieOrder.builder().userPhone(movieOrderFrom.getUserPhone()).orderMoney(s)
                .orderWithdraw(null).userId(1).createTime(CommonUtil.dataLocalDatePares()).orderId(new BigInteger(CommonUtil.getOrderNum())).build();
        Integer integer = baseMapper.addMovieOrder(build);
        if (integer<=0) throw new MainExection(500,"创建订单失败");
        //日志记录
//        Message<OrderLogConsumerFrom> integerMessage=MessageBuilder.withPayload(OrderLogConsumerFrom.builder().orderId(build.getOrderId()).orderLog("创建订单成功").userId(build.getUserId()).build()).build();
//        rocketMQTemplate.asyncSend("order_log", integerMessage, new SendCallback() {
//            @Override
//            public void onSuccess(SendResult sendResult) {
//                System.out.println("生成日志成功");
//            }
//
//            @Override
//            public void onException(Throwable throwable) {
//                System.out.println(throwable);
//            }
//        });
        BigInteger orderId=build.getOrderId();
        this.orderLogConsumer(OrderLogConsumerFrom.builder().orderId(build.getOrderId()).orderLog("创建订单成功").userId(build.getUserId()).build());
        //将订单id录入票务id
        //加锁
        Lock lock=new ReentrantLock();
        //通过场次获取属性
        List<MovieTicketing> movieTicketings=new ArrayList<>();
        List<OrderCreateConsumerFrom> orderCreateConsumerFroms =new ArrayList<>();
        for (Integer ticketingId : ticketingIds) {
            MovieTicketing movieTicketing = movieTicketingService.getById(ticketingId);
            lock.lock();
            Object o = ort.opsForHash().get("numberOfSessionsId:" + numberOfSessionsId.toString(), "ticketingId" + movieTicketing.getTicketingId().toString());
            if (o==null) throw new MainExection(500,movieTicketing.getTicketingId()+"的票务已被购买");
            Long delete = ort.opsForHash().delete("numberOfSessionsId:" + numberOfSessionsId.toString(), "ticketingId" + movieTicketing.getTicketingId().toString());
            if (delete<=0) throw new MainExection(500,movieTicketing.getTicketingId()+"的票务创建订单 移除redis数据失败");
            lock.unlock();
            movieTicketing.setOrderId(build.getOrderId());
            movieTicketings.add(movieTicketing);
            //消息队列参数
            OrderCreateConsumerFrom orderCreateConsumerFrom = OrderCreateConsumerFrom.builder().orderId(build.getOrderId()).numberOfSessionsId(numberOfSessionsId).ticketingId(movieTicketing.getTicketingId()).build();
            orderCreateConsumerFroms.add(orderCreateConsumerFrom);
        }
        boolean b = movieTicketingService.updateBatchById(movieTicketings);
        if (!b)throw new MainExection(500,"票务更改状态失败");
        //设置订单过期时间 redis
        ort.opsForValue().set("order:id:"+build.getOrderId(),"订单存在",15, TimeUnit.MINUTES);
        //设置消息队列延时消息
        Message<List<OrderCreateConsumerFrom>> message=MessageBuilder.withPayload(orderCreateConsumerFroms).build();
        rocketMQTemplate.syncSend("order_create",message,3000,15);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String payOrder(BigInteger orderid) throws MainExection, AlipayApiException {
        //设置消息队列延时消息
        Message<BigInteger> message=MessageBuilder.withPayload(orderid).build();
        rocketMQTemplate.syncSend("order_pay_order",message,3000,8);
        QueryWrapper<MovieOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_start",2);
        queryWrapper.eq("order_id",orderid);
        MovieOrder movieOrder = baseMapper.selectOne(queryWrapper);
        if (movieOrder ==null) throw new MainExection(500,"该订单不存在或状态不为待支付");
        //获取订单 查看订单是否过期
        Object o = ort.opsForValue().get("order:id:" + orderid);
        if (o==null){
            throw new MainExection(500,"订单已过期");
        }
        //写出支付支付界面
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = movieOrder.getOrderId().toString();
        //付款金额，必填
        String total_amount = movieOrder.getOrderMoney();
        //订单名称，必填
        String subject = "购票订单:"+movieOrder.getOrderId();
        //商品描述，可空
        String body = "这是一个测试商品";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String body1 = alipayClient.pageExecute(alipayRequest).getBody();
        //this.orderLogConsumer(OrderLogConsumerFrom.builder().orderId(movieOrder.getOrderId()).orderLog("开启支付宝支付").userId(movieOrder.getUserId()).build());
        return body1;
    }

    @Override
    public void notify(ServletRequest request, ServletResponse response) throws AlipayApiException, UnsupportedEncodingException, MainExection {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//		valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                BigInteger orderId = new BigInteger(out_trade_no);
                MovieOrder movieOrder = baseMapper.selectById(orderId);
                movieOrder.setOrderStart(3);
                int i = baseMapper.updateById(movieOrder);
                if (i>0) {
                    System.out.println("订单支付成功");
                    //查询出订单对应的电影id 增加票房
                    QueryWrapper<MovieTicketing> queryWrapper=new QueryWrapper<>();
                    queryWrapper.eq("order_id",orderId);
                    List<MovieTicketing> list = movieTicketingService.list(queryWrapper);
                    if (list ==null || list.size()==0)throw new MainExection(500,"不存在对应的票务");
                    Integer productId = list.get(0).getProductId();
                    //修改电影中的票房数据
                    Result<Boolean> booleanResult = movieFeignClient.addMoney(MovieAddMoneyFrom.builder().id(productId).money(movieOrder.getOrderMoney()).build());
                    //生成取票码
                    if (booleanResult.getCode()==200){
                        String randomUUID = CommonUtil.randomUUID();
                        movieOrder.setOrderWithdraw(randomUUID);
                        int updateById = baseMapper.updateById(movieOrder);
                        if (updateById<0)throw new MainExection(500,"生成二维码失败");
                    }else{
                        System.out.println("修改票房失败");
                    }
                    //存入评分
                    for (MovieTicketing movieTicketing : list) {
                        ort.opsForValue().set("score:Ticketing_id"+movieTicketing.getTicketingId(),"-1",3,TimeUnit.DAYS);
                    }
                } else {
                    System.out.println("订单支付失败");
                    throw new MainExection(500,"订单修改状态失败");
                }

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }

        } else {//验证失败
            System.out.println("fail");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String refund(BigInteger orderid) throws AlipayApiException, MainExection {
        //对订单进行操作
        MovieOrder movieOrder = baseMapper.selectById(orderid);
        if (movieOrder ==null) throw new MainExection(500,"订单不存在");
        if (movieOrder.getOrderStart()!=3)throw new MainExection(500,"订单状态不为已支付");
        movieOrder.setOrderStart(5);
        int updateById = baseMapper.updateById(movieOrder);
        if (updateById<=0) throw new MainExection(500,"修改订单状态失败");
        //进行票房操作
        //查询出订单对应的电影id 增加票房
        QueryWrapper<MovieTicketing> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id",orderid);
        List<MovieTicketing> list = movieTicketingService.list(queryWrapper);
        if (list ==null || list.size()==0)throw new MainExection(500,"不存在对应的票务");
        Integer productId = list.get(0).getProductId();
        Result<Boolean> booleanResult = movieFeignClient.addMoney(MovieAddMoneyFrom.builder().id(productId).money("-"+movieOrder.getOrderMoney()).build());
        if (booleanResult.getCode()!=200)throw new MainExection(500,"票房修改失败");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //商户订单号，必填
        String out_trade_no = new String(orderid.toString());
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = new String(movieOrder.getOrderMoney());
        //标识一次退款请求，同一笔交易多次退款需要保证唯一。如需部分退款，则此参数必传；不传该参数则代表全额退款
        String out_request_no = new String(UUID.randomUUID().toString());
        // 字符转义很重要
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //输出
        return result;
    }

    @Override
    public String queryOrder(BigInteger orderid) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderid.toString() + "\"," +
                "\"trade_no\":\"" + "" + "\"," +
                "\"org_pid\":\"" + "" + "\"," +
                "      \"query_options\":[" +
                "        \"TRADE_SETTLE_INFO\"" +
                "      ]" +
                "  }");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println("【查询返回交易状态】" + response.getTradeStatus());
        return response.getTradeStatus();
    }

    @Override
    public Boolean OrderScore(BigInteger orderid, Integer score) throws MainExection {
        MovieOrder movieOrder = baseMapper.selectById(orderid);
        if (movieOrder ==null) throw new MainExection(500,"订单不存在");
        if (movieOrder.getOrderStart()!=3)throw new MainExection(500,"订单状态不为已支付");
        QueryWrapper<MovieTicketing> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id",orderid);
        List<MovieTicketing> movieTicketings = movieTicketingService.list(queryWrapper);
        if (movieTicketings!=null &&movieTicketings.size()>0){
            List<MovieScoreFrom> movieScoreFroms=new ArrayList<>();
            MovieScoreListFrom movieScoreListFrom=new MovieScoreListFrom();
            for (MovieTicketing movieTicketing : movieTicketings) {
                MovieScoreFrom movieScoreFrom=new MovieScoreFrom();
                movieScoreFrom.setOrderId(movieTicketing.getOrderId());
                movieScoreFrom.setProductId(movieTicketing.getProductId());
                movieScoreFrom.setScore(score);
                movieScoreFrom.setTicketingId(movieTicketing.getTicketingId());
                movieScoreFroms.add(movieScoreFrom);
            }
            movieScoreListFrom.setMovieScoreFromList(movieScoreFroms);
            Result<Boolean> booleanResult = movieFeignClient.addScore(movieScoreListFrom);
            if (booleanResult.getCode()!=200)throw new MainExection(500,"电影服务导致评分失败");
            return true;
        }else throw new MainExection(500,"该订单下不存在票务");
    }

    //获取验证码
    @Override
    public String iphoneMa(String iphone) throws MainExection {
        if (iphone==null || "".equals(iphone)){
            throw new MainExection(500,"电话号码不能为空");
        }
        //定义一个字符串变量 记录生成的随机数
        String code = "";
        Random r = new Random();
        //2.在方法内部使用for循环生成指定位数的随机字符，并连接起来
        for (int i = 0; i <= 5; i++) {
            //生成一个随机字符：大写 ，小写 ，数字（0  1  2）
            int type = r.nextInt(3);
            switch (type) {
                //大写字母  65   ~   65+25
                case 0:
                    char ch = (char) (r.nextInt(26) + 65);
                    code += ch;
                    break;
                //小写字母  90   ~   97+25
                case 1:
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                //大写字母  65   ~   65+25
                case 2:
                    code +=  r.nextInt(10);
                    break;
            }
        }
        ort.opsForValue().set("iphone:"+iphone,code,10,TimeUnit.MINUTES);
        return code;
    }

    @Override
    public MovieOrder getOrder(BigInteger orderid) throws MainExection {
        MovieOrder movieOrder = baseMapper.selectById(orderid);
        if (movieOrder==null) throw new MainExection(500,"订单不存在");
        return movieOrder;
    }

    //日志消息队列
    public void orderLogConsumer(OrderLogConsumerFrom orderLogConsumerFrom){
        Message<OrderLogConsumerFrom> integerMessage=MessageBuilder.withPayload(orderLogConsumerFrom).build();
        rocketMQTemplate.asyncSend("order_log", integerMessage, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("生成日志成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable);
            }
        });
    }

}
